package com.example.demo.controller;

import com.example.demo.pojo.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;

@Controller
public class LoginController {

    @GetMapping("/isLogin")
    @ResponseBody
    public Object getUserInfo(){
        if(!SecurityContextHolder.getContext().getAuthentication().getName().equals("anonymousUser")){
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            //获取登录的用户名
            String username = authentication.getName();
            System.out.println("username:"+username);

            //用户的所有权限
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            System.out.println("authorities:"+authorities);

            /**
             * 如果要获取更详细的用户信息可以采用下面这种方法
             */
            //用户的基本信息
//            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//            System.out.println("user:"+user);

            //用户的id
//            Integer userId = user.getId();
//            System.out.println("userId: "+userId);

            return "已登录账号："+username;

        }
        else{
            return "请先登录";
        }
    }
}
